﻿using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

namespace Admin.NET.Core.Btms;

/// <summary>
/// 只读库，只能执行select语句，不能执行存储过程等其他语句
/// </summary>
public class ReadOnlyDbManager : IScoped
{
    private readonly ISqlSugarClient _db;
    private readonly IServiceScope _serviceScope;

    // 旧的写法
    //public DataBaseManager(ISqlSugarClient db)
    //{
    //    _db = db;
    //}

    public ReadOnlyDbManager(IServiceScopeFactory scopeFactory)
    {
        _serviceScope = scopeFactory.CreateScope();
        // _db = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>();

        // 只读库，只能执行select语句，不能执行存储过程等其他语句
        _db = SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.ReadOnlyDataBaseConfigId);
    }

    /// <summary>
    /// 基于sql语句进行参数化查询一个表格，并且返回json格式的数组
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public DataTable QueryToDataTable(string sql, List<SugarParameter> parameter)
    {
        // 1,SQL预处理
        if (string.IsNullOrWhiteSpace(sql))
        {
            return new DataTable();
        }

        var beginIndex = sql.IndexOf("--declare-end");
        if (beginIndex > 0)
        {
            sql = sql.Substring(beginIndex + 1);
        }
        beginIndex = sql.IndexOf("-- declare-end");
        if (beginIndex > 0)
        {
            sql = sql.Substring(beginIndex + 1);
        }
        sql = sql.Replace("\\r\\n", Environment.NewLine); //windows环境
        sql = sql.Replace("\\n", Environment.NewLine); //linux环境
        sql = sql.Replace("\\r", Environment.NewLine); //macos环境
        sql = sql.Replace("\\t", "  "); // \t处理为空格

        if (string.IsNullOrWhiteSpace(sql))
        {
            return new DataTable();
        }

        // 2,参数化查询
        var table = _db.Ado.GetDataTable(sql, parameter);
     
        return table;
    }
}
